package topic.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import common.BaseActivity;
import common.Constant;
import https.InterNetController;
import in.srain.cube.views.ptr.PtrFrameLayout;
import topic.adapter.TopicAdapter;
import topic.bean.TopicGroupBean;
import utils.MyLogUtils;
import view.MyImageLoader;
import view.MyPtrRefresh_LoadView;

/**
 * Created by Administrator on 2017/3/23.
 * 某个话题的主页
 */
@ContentView(R.layout.single_topic)
public class SingleTopic extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.single_topic_lv)
    private ListView single_topic_lv;
    @ViewInject(R.id.single_topic_loadLayout)
    private MyPtrRefresh_LoadView single_topic_loadLayout;
    @ViewInject(R.id.single_topic_headerLayout)
    private RelativeLayout single_topic_headerLayout;
    @ViewInject(R.id.single_topic_back)
    private ImageView single_topic_back;
    private TextView single_topic_title1;//头部里面的title
    @ViewInject(R.id.single_topic_title)
    private TextView single_topic_title;//隐藏的title
    @ViewInject(R.id.single_topic_comment_ima)
    private ImageView single_topic_comment_ima;
    private View headerView;
    private TextView single_topic_focus_topic;//关注话题
    private ImageView single_topic_ima;
    private TopicAdapter topicAdapter;
    private ArrayList<TopicGroupBean.BlogListBean> arrayList;
    private String topicid;

    private int page = 1;


    private final int GET_DATA = 0;
    private final int ATTENTION_TOPIC = 1;
    private boolean changeFocus = false;
    private static final String TAG = "SingleTopic";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS://成功返回
                    if (msg.arg1 == ATTENTION_TOPIC) {
                        try {
                            JSONObject jsonObject = new JSONObject(String.valueOf(msg.obj));
                            String status = jsonObject.getString("status");
                            if ("0".equals(status)) {
                                //取关
                                single_topic_focus_topic.setTextColor(getResources().getColor(R.color.white));
                                single_topic_focus_topic.setBackgroundResource(R.drawable.shape_transparent);
                                changeFocus = true;
                            }else{
                                //关注成功
                                single_topic_focus_topic.setTextColor(getResources().getColor(R.color.common_color));
                                single_topic_focus_topic.setBackgroundResource(R.drawable.shape_transparent_blue);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }else {
                        Gson gson = new Gson();
                        TopicGroupBean topicGroupBean = gson.fromJson((String) msg.obj, TopicGroupBean.class);
                        if (page == 1) {
                            List<TopicGroupBean.TopicListBean> topicList = topicGroupBean.getTopicList();
                            if (topicList != null) {
                                if (topicList.size() > 0) {
                                    for (int i = 0; i < topicList.size(); i++) {
                                        if (topicid.equals(topicList.get(i).getId())) {
                                            single_topic_title1.setText(topicList.get(i).getTitle());
                                            if ("0".equals(topicList.get(i).getAttentioned())) {
                                                single_topic_focus_topic.setTextColor(getResources().getColor(R.color.white));
                                                single_topic_focus_topic.setBackgroundResource(R.drawable.shape_transparent);
                                            } else {
                                                single_topic_focus_topic.setTextColor(getResources().getColor(R.color.common_color));
                                                single_topic_focus_topic.setBackgroundResource(R.drawable.shape_transparent_blue);
                                            }
                                            MyImageLoader.showImage(topicList.get(i).getImage(), single_topic_ima);
                                        }
                                    }
                                }
                            }
                        }
                        if (topicGroupBean != null) {
                            List<TopicGroupBean.BlogListBean> blogList = topicGroupBean.getBlogList();
                            if (blogList != null) {
                                if (page == 1) {
                                    arrayList.clear();
                                }
                                for (int i = 0; i < blogList.size(); i++) {
                                    TopicGroupBean.BlogListBean blogListBean = blogList.get(i);
                                    arrayList.add(blogListBean);
                                }
                                topicAdapter.notifyDataSetChanged();
                            }
                        } else {
                            page--;
                        }
                        if (single_topic_loadLayout != null) {
                            single_topic_loadLayout.OnRefreshComplete();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        topicid = getIntent().getStringExtra("topicid");
        MyLogUtils.e(TAG, "" + topicid);
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        getDataFromInterNet(page);
    }

    private void initView() {
        single_topic_back.setOnClickListener(this);
        single_topic_comment_ima.setOnClickListener(this);
        headerView = LayoutInflater.from(this).inflate(R.layout.single_topic_header, null);
        single_topic_title1 = (TextView) headerView.findViewById(R.id.single_topic_title1);
        single_topic_ima = (ImageView) headerView.findViewById(R.id.single_topic_ima);
        single_topic_focus_topic = (TextView) headerView.findViewById(R.id.single_topic_focus_topic);
        single_topic_focus_topic.setOnClickListener(this);

        final int[] location = new int[2];
        single_topic_loadLayout.ChangeMode(false,true);
        single_topic_loadLayout.setMyScrollListener(new MyPtrRefresh_LoadView.MyOnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                headerView.getLocationOnScreen(location);
                int measuredHeight = headerView.getMeasuredHeight();
                if (firstVisibleItem <= 0) {
                    if (Math.abs(location[1]) <= (measuredHeight - single_topic_headerLayout.getMeasuredHeight())) {
                        float scale = (float) (location[1]) / (measuredHeight - single_topic_headerLayout.getMeasuredHeight());
                        float alpha = (255 * Math.abs(scale));
                        // 只是layout背景透明(仿知乎滑动效果)
                        single_topic_headerLayout.setBackgroundColor(Color.argb((int) alpha, 8, 130, 238));
                        single_topic_title.setTextColor(Color.argb((int) alpha, 255, 255, 255));
                    } else {
                        single_topic_headerLayout.setBackgroundColor(Color.argb(255, 8, 130, 238));
                        single_topic_title.setTextColor(Color.argb(255, 255, 255, 255));
                    }
                } else {
                    single_topic_headerLayout.setBackgroundColor(Color.argb(255, 8, 130, 238));
                    single_topic_title.setTextColor(Color.argb(255, 255, 255, 255));
                }
            }
        });
        single_topic_loadLayout.setMyPtrHandler(new MyPtrRefresh_LoadView.MyPtrHandler() {

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                getDataFromInterNet(++page);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {

            }
        });
        arrayList = new ArrayList<>();
        topicAdapter = new TopicAdapter(this, arrayList, new TopicAdapter.OnTopicDetailListener() {
            @Override
            public void onTopicDetailListener(int position) {
                Intent i = new Intent(SingleTopic.this, TopicDetail.class);
                i.putExtra("blogid", arrayList.get(position).getBlogid());
                startActivityForResult(i, position);
            }
        });
        single_topic_lv.addHeaderView(headerView);
        single_topic_lv.setAdapter(topicAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.single_topic_back:
                Intent i1 = new Intent();
                i1.putExtra("changeFocus",changeFocus);
                this.setResult(1,i1);
                SingleTopic.this.finish();
                break;
            case R.id.single_topic_focus_topic:
                //关注话题
                focusTopic();
                break;

            case R.id.single_topic_comment_ima:
                if(hasLoad()) {
                    Intent i = new Intent(this, DeliverBlog.class);
                    i.putExtra("topicid", topicid);
                    startActivity(i);
                }else{
                    login(this);
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        Intent i1 = new Intent();
        i1.putExtra("changeFocus",changeFocus);
        this.setResult(1,i1);
        SingleTopic.this.finish();
    }

    private void getDataFromInterNet(int page) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("topicid", topicid);
        hashMap.put("page", String.valueOf(page));
        new InterNetController(this, Constant.SHOWBLOG, handler, hashMap, GET_DATA);
    }

    private void focusTopic() {
        //关注话题
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("topicid", topicid);
        new InterNetController(this, Constant.TOPICATTENTION, handler, hashMap, ATTENTION_TOPIC,false);
    }

}
